package com.hello.sky.service.impl;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hello.sky.constant.MessageConstant;
import com.hello.sky.constant.StatusConstant;
import com.hello.sky.exception.SkyException;
import com.hello.sky.mapper.CategoryMapper;
import com.hello.sky.mapper.DishMapper;
import com.hello.sky.mapper.SetmealMapper;
import com.hello.sky.model.dto.CategoryDTO;
import com.hello.sky.model.entity.Category;
import com.hello.sky.model.dto.PageParamDto;
import com.hello.sky.model.entity.Dish;
import com.hello.sky.model.entity.Setmeal;
import com.hello.sky.model.vo.DishVO;
import com.hello.sky.result.PageResult;
import com.hello.sky.service.CategoryService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author D
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String CACHE_PREFIX = "category_";

    @Override
    public PageResult getPage(PageParamDto pageParamDto) {

        LambdaQueryWrapper<Category> qr = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(pageParamDto.getName())) qr.like(Category::getName, pageParamDto.getName());
        if (pageParamDto.getType() != null) qr.eq(Category::getType, pageParamDto.getType());
        qr.orderBy(true, true, Category::getSort);

        Page<Category> paged = page(
                new Page<Category>(pageParamDto.getPage(), pageParamDto.getPageSize()),
                qr);
        return new PageResult(paged.getTotal(), paged.getRecords());
    }

    @Override
    public List<Category> getListByType(Integer type) {
        // 先查缓存
        String cachedList = (String) redisTemplate.opsForValue().get(CACHE_PREFIX + type);
        List<Category> categoryList = null;

        if (cachedList != null) {
            // 将缓存中的对象转换为 List<Category>
            categoryList = JSON.parseArray(cachedList, Category.class);

            log.warn("查询缓存成功，类型：{}", type);
        } else {
            // 从数据库查询数据
            categoryList = categoryMapper.getListByType(type);
            // 将查询结果存入缓存
            redisTemplate.opsForValue().set(CACHE_PREFIX + type, JSON.toJSONString(categoryList));
            log.warn("查询数据库，类型：{}", type);
        }
        return categoryList;
    }

    @Override
    public void addCategory(CategoryDTO dto) {
        Category category = new Category();
        BeanUtils.copyProperties(dto, category);
        category.setStatus(StatusConstant.DISABLE);
        categoryMapper.addCategory(category);
        delCache();
    }

    @Override
    public void updateStatus(Integer status, Integer id) {
        Category category = new Category();
        category.setStatus(status);
        category.setId(Long.parseLong(String.valueOf(id)));
        categoryMapper.updateCategory(category);
        delCache();
    }

    @Override
    public void delCategoryById(Integer id) {
        //分类正在使用，不能删除
        Category category = baseMapper.selectById(id);
        if (category.getStatus() == StatusConstant.ENABLE) throw SkyException.cast(MessageConstant.CATEGORY_IS_ENABLE);
        //分类关联了菜品,不能删除
        Long dishCount = dishMapper.selectCount(new QueryWrapper<Dish>().eq("category_id", id));
        if (dishCount > 0) throw SkyException.cast(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        //分类关联了套餐,不能删除
        Long setmealCount = setmealMapper.selectCount(new QueryWrapper<Setmeal>().eq("category_id", id));
        if (setmealCount > 0) throw SkyException.cast(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        //删除
        categoryMapper.delCategoryById(id);
        delCache();
    }

    @Override
    public void updateCategory(Category category) {
        categoryMapper.updateCategory(category);
        delCache();
    }

    @Override
    public List<DishVO> getDishById(Long categoryId) {
        List<Dish> dishList = dishMapper.getDishByCategoryId(categoryId);
        return dishList.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            return dishVO;
        }).collect(Collectors.toList());
    }

    private void delCache(){
        //删除未启用，已启用，所有分类分类
        String[] keys = {CACHE_PREFIX + null, CACHE_PREFIX + StatusConstant.ENABLE, CACHE_PREFIX + StatusConstant.DISABLE};
        redisTemplate.delete(Arrays.asList(keys));
    }
}
